﻿using IMES.Common.Domain.KeepModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Globalization;

namespace Keep.API.Appliction.Command.Select
{
	/// <summary>
	/// 导入功能
	/// </summary>
	public class ImportFunctionHandler:IRequestHandler<ImportFunctionCommon,Result>
	{
		private readonly IBaseRepositorys<workSheet> _workSheetRep;
		/// <summary>
		/// 导入功能
		/// </summary>
		/// <param name="workSheetRep"></param>
		public ImportFunctionHandler(IBaseRepositorys<workSheet> workSheetRep)
		{
			_workSheetRep = workSheetRep;
		}


		public async Task<Result> Handle(ImportFunctionCommon request, CancellationToken cancellationToken)
		{
			var result = new Result() { Code = 0, Messege = "导入失败" };
			try
			{
				//获取文件扩展名 判断上传的文件类型是否正确
				var ext = Path.GetExtension(request.file.FileName);
				if (ext == ".xls" || ext == ".xlsx")
				{

				}
				else
				{
					result.Messege = "您上传的文件类型不正确";
					return result;
				}
				using (MemoryStream ms = new MemoryStream())
				{
					request.file.CopyTo(ms);
					ms.Position = 0;
					//根据文件扩展名创建对应的工作簿对象(HSSFWorkbook用于.xls，XSSFWorkbook用于.xlsx)
					//获取工作簿
					IWorkbook wb = null;
					if (ext == ".xls")//创建97-2003
					{
						wb = new HSSFWorkbook(ms);
					}
					else//创建2007及以上版本
					{
						wb = new XSSFWorkbook(ms);
					}
					//获取sheet 获取工作簿中的第一个工作表
					ISheet sheet = wb.GetSheetAt(0);
					int totalRows = sheet.LastRowNum;//总行数
					int totalCells = sheet.GetRow(0).LastCellNum;//总列数

					// 创建一个用于存储解析后的数据的列表
					var workSheet = new List<workSheet>();
					//循环总行数 开头必须是1 不然从表头开始
					//遍历工作表的每一行（从第二行开始，因为第一行通常是表头）
					for (int i = 1; i <= totalRows; i++)
					{
						//获取当前行
						IRow row = sheet.GetRow(i);

						//这个类必须写到循环里边 不然你批量添加只能添加一行
						var dto = new workSheet();// 在循环内创建新的对象实例

						//下标从0开始 导入时 外键需进行判断 客户不知道你是外键 只会输入文字 需要在后台判断
						/* var earnumber = row.GetCell(0).ToString();
						 var basic = BasicInformationRepository.GetAll().Where(z => z.Auricle == earnumber).FirstOrDefault();
						 dto.BreedingSheepArchiveId = basic.BreedingSheepArchiveId;*/

						//日期转换
						//日期在excel表中必须是年月日格式 但不能加时分秒 (注意!!!!)
						string inputDate = row.GetCell(4).ToString();
						string[] multipleFormats = { "dd-M月-yyyy", "yyyy-M-dd" };
						DateTime parsedDate;
						foreach (var format in multipleFormats)
						{
							if (DateTime.TryParseExact(inputDate, new[] { format }, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
							{
								dto.CreateDate = Convert.ToDateTime(parsedDate.ToString("yyyy-MM-dd"));
								break;//成功解析后跳出循环
							}
						}

						dto.WorkSheetNumber = row.GetCell(0).ToString();
						dto.ProductNumber = row.GetCell(1).ToString();
						dto.Numberofpackages =Convert.ToInt32(row.GetCell(2));
						dto.ScheduledStartTime = Convert.ToDateTime(row.GetCell(3).ToString());
						dto.ScheduledEndTime = Convert.ToDateTime(row.GetCell(4).ToString());
						dto.StartTime = Convert.ToDateTime(row.GetCell(5).ToString());
						dto.EndTime = Convert.ToDateTime(row.GetCell(6).ToString());
						dto.State = (WorkSheetState)(row.GetCell(7).ToString() == "开发部" ? 1 : row.GetCell(3).ToString() == "管理部" ? 2 : 3);
						dto.Remark = row.GetCell(8).ToString();
						dto.TaskIds = "";
						dto.CreateName = "小罗";
						dto.UpdateId = null;
						dto.UpdateName = null;
						dto.UpdateDate = null;
						dto.DeleteId = null;
						dto.DeleteName = null;
						dto.DeleteDate = false;
						result.Code = 0;
						result.Messege = "导入成功";
						_workSheetRep.Add(dto);
					}

				}
			}
			catch (Exception)
			{

				throw;
			}
			return result;
		}



	}
}
